<html>
<head>
    <meta charset="utf-8">
    <title>歌词学日文</title>

    <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="//cdn.bootcss.com/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.9.2.custom.css"
          rel="stylesheet">

    <script src="//cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/jquery-ui-bootstrap/0.5pre/js/jquery-ui-1.9.2.custom.min.js"></script>
    <script src="//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--    <script src="//cdn.bootcss.com/bootstrap/3.3.7/js/npm.js"></script>-->
</head>
<body>
<span>asdasfjskdhnfjks</span>
<br>
asdfd dfdfh asjbfhj sdnfbjhsgf asnbdj
<button> asdfass</button>

<div class="container">
    <div class="row">
        <div class="row">
            <label for=""> </label>
            <textarea id="" class="form-control" style="height: 800px"></textarea>
        </div>
        <div class="row">
            <label for=""></label>
            <textarea id="" class="form-control"></textarea>
        </div>
    </div>
</div>


<!--面板-->
<div class="panel panel-info" style="width: 300px;">
    <div class="panel-heading">
        <h3 class="panel-title">
            <span id="panel-title-name">残像</span>
            <a class="btn-default btn pull-right" style="margin-top: -8px;">x</a>
        </h3>
    </div>
    <div class="panel-body">
        <div>
            <span>[ざんぞう]</span>
            <span>[zannzou]</span>
            声调：<span>◎</span>
            <audio class="audio" src="http://d1.g.hjfile.cn/voice/jpsound/J46247.mp3" controls autoplay></audio>
            <!--            playcount="2"-->
            <!-- 控制淡入效果 -->
            <!--            <button id="audiofadein" class="btn btn-default" title="播放mp3"><i-->
            <!--                    class="glyphicon glyphicon-volume-up"></i></button>-->
        </div>
        <div>
                <span>【名词】 余像，残像。对光刺激凝视片刻后，闭上眼睛或把视线移往别处时产生的视觉体验。出现种种形状，颜色，亮度的像。（光の刺激を見つめたあと、目を閉じたり他の方面に視線を移したりしたときに生じる視覚体験。種々の形･色･明るさの像として現れる。）あれは遠い街の残像，巡り巡る甘い追憶。/那是遥远街区的残像，循环上演的甜美追忆。
                </span>
        </div>
    </div>
</div>

<script type="text/javascript">
    /**
     * 划词类
     */
    var Word = {
        //计时器
        timer: 0,
        $searchBox: null,
        //开始选择时的对象
        startObj: null,
        //是否开启了划词
        allow: true,
        //要搜索的字符串
        searchStr: "",
        init: function () {
            this.$searchBox = $('<div id="GLSearch" class="btn btn-info" style="z-index: 101">' +
                '<span class="glyphicon glyphicon-search">搜索</span>' +
                '<span id="word"></span></div>').hide().appendTo(document.body);
            this.$searchBox.click(searchWord.get);
        },
        toggleOpen: function () {
            if (Word.allow) {
                Word.allow = false;
                alert('Google搜索已关闭');
            }
            else {
                Word.allow = true;
                alert('Google搜索已打开');
            }
        },
        /**
         * 获得选择的文本
         */
        getUserSelection: function () {
            return window.getSelection ? window.getSelection().toString() : document.selection.createRange().text;
        },
        /**
         * 鼠标按下
         * @param event
         */
        mousedown: function (event) {
            event = (event) ? event : ((window.event) ? window.event : "");
            if (event) {
                //用户当前没有选择东西，才开始
                if (Word.getUserSelection() == "") {
                    Word.startObj = (event.target) ? event.target : event.srcElement;
                }
            }
        },
        /**
         * 鼠标弹起
         * @param event 事件object
         */
        mouseup: function (event) {
            event = (event) ? event : ((window.event) ? window.event : "");
            if (event) {
                //事件发生对象
                var event_target = (event.target) ? event.target : event.srcElement;

                //停掉正在运作的计时器
                if (Word.timer > 0) {
                    clearTimeout(Word.timer);
                }

                Word.startObj = null;

                //对这些标签就跳过
                var taglist = ["BUTTON", "A"];

                //检查点击的元素是否在搜索框内
                var inBox = ( $(event_target).parents("#GLSearch").length > 0 || event_target.id == "GLSearch");
                if ($.inArray(event_target.tagName, taglist) == -1
//                        && event_target.tagName != "INPUT"
//                        && event_target == Word.startObj
                    //&& $(Word.startObj).get(0) == $(':focus').get(0)
                    //该元素的不是搜索框的子元素
                    && !inBox
                    && Word.allow) {

                    Word.timer = setTimeout(function () {
                        //选择的单词
                        var strSelection = Word.getUserSelection();
                        if (strSelection.length > 0) {
                            Word.search(strSelection, event);
                        } else {
                            Word.searchStr = "";
                            Word.$searchBox.slideUp();
                        }
                    }, 100);
                }
                else {
                    //如果不在搜索框内就隐藏搜索按钮
                    if (!inBox) {
                        Word.searchStr = "";
                        Word.$searchBox.slideUp();
                    }
                }

            }
        },
        /**
         * 弹出搜索按钮
         * @param str
         * @param event
         */
        search: function (str, event) {
            this.$searchBox.slideDown();
            if (str.toString().length > 0) {
                this.$searchBox.css({
                    'display': 'block',
                    'position': 'absolute',
                    'zindex': '500'
                });
                /**
                 *获取鼠标位置
                 */
                var getMousePos = function (ev) {
                    if (!ev) {
                        ev = this.getEvent();
                    }
                    if (ev.pageX || ev.pageY) {
                        return {
                            x: ev.pageX,
                            y: ev.pageY
                        };
                    }

                    if (document.documentElement && document.documentElement.scrollTop) {
                        return {
                            x: ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
                            y: ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
                        };
                    }
                    else if (document.body) {
                        return {
                            x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                            y: ev.clientY + document.body.scrollTop - document.body.clientTop
                        };
                    }
                };
                var pos = getMousePos(event);
                this.$searchBox.css("top", pos.y);
                this.$searchBox.css("left", pos.x);
                this.$searchBox.find("#word").text(str);

                this.searchStr = str;
//                Word.$searchBox.html("<a class='GL_s' target='_blank' href='https://www.google.com/search?ie=UTF-8&oe=UTF-8&q=" + encodeURIComponent(str) + "'>Google搜索</a>");
            }
        }
    };

    /**
     * 搜索控制类
     */
    var searchWord = {
        _word: {
            word: "",
            jieshi: "",
            mp3: "",
            sheng: "",
            luoma: "",
            kana: ""
        },
        /**
         * 搜索按钮被点击，发送ajax请求
         */
        get: function () {
            /**
             * ajax请求
             */
            $.ajax({
                url: "start.php",
                type: "POST",
                datatype: "json",
                timeout: 3000,
                data: {
                    w: Word.searchStr
                },
                success: function (rdata, textStatus) {
                    searchWord.handleResult(rdata);
//                    var data = $.parseJSON(rdata);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + textStatus + errorThrown);
                }
            });
        },
        /**
         * 处理ajax的结果
         * @param data
         */
        handleResult: function (data) {
            console.log(data);
//            success: true
//            word: Object
//            jieshi: "  【自动词・サ变/三类】 （1）一起，一块。一緒に行く。/一块儿去。彼も一緒になって笑った。/他也和大家一同笑了。みな一緒に写真をとる。/大家在一起照相。よかったらご一緒しましょう。/方便的话我陪你（们）一起去吧。（2）同样，一样。君の意見もぼくと一緒だ。/你的意见也和我一样。（3）共同行动。手紙と一緒に送る。/连同信一起寄出。3か月分の手当を一緒に受け取る。/三个月的津贴一起领。全部一緒にするといくらになりますか。/一共多少钱？その国はドイツとフランスを一緒にしたくらい大きい。/那个国家有德法两国合起来那么大。別々に出かけ,途中で一緒になる。/分别出发在途中会合。好いた同士を一緒にする。/使相爱的两个人结婚。（4）同时，一齐。そう一緒に口を出しては困る。/大家这么一齐说可不好办。盆と正月が一緒にくる。/中元节和新年同时来了；双喜临门。（5）《相关惯用语》一緒になる。/结婚。"
//            kana: "[いっしょ]"
//            luoma: "[issho]"
//            mp3: "http://d1.g.hjfile.cn/voice/jpsound/J04295.mp3"
//            sheng: "◎"
//            word: "一緒"

            if (!data.success) {
                alert(data.msg);
                return;
            }

            //这个单词实体
            var the_word = data.word;

            //创建面板
            var panel = new Panel;
            panel.create(the_word.word);

            //根据data创建html元素
            var Panel_body_html =
                ['<div>',
                    '<span id="kana"></span>',
                    '<span id="luoma"></span>',
                    '声调：<span id="sheng"></span>',
                    '<audio id="mp3" class="audio" src="" controls autoplay style="width:100%;"></audio>',
                    '</div>',
                    '<div style="height: 100px;">',
                    '<span id="jieshi"></span>',
                    '</div>'].join("");
            var $Pbody = $(Panel_body_html);

            $Pbody.find('#kana').text(the_word.kana);
            $Pbody.find('#luoma').text(the_word.luoma);
            $Pbody.find('#sheng').text(the_word.sheng);
            $Pbody.find('#mp3').attr("src", the_word.mp3);

            panel.setBody($Pbody);
            panel.$Panel.css("top", Word.$searchBox.css("top"));
            panel.$Panel.css("left", Word.$searchBox.css("left"));


            //解释部分
            var str_jieshi = the_word.jieshi;
            var $jieshi = $Pbody.find('#jieshi');
            if (str_jieshi.length > 80) {
                //显示更多
                var $show_more = $('<div id="showmore" style="color: blue;cursor: pointer">显示更多</div>').appendTo(panel.$panel_body).data("show",false);


                //截取字符串显示
                var str_sub = str_jieshi.substr(0, 80);
                $jieshi.text(str_sub+"...");

                $show_more.click(function () {
                    var $this = $(this);
                    console.log($this.data("show"));
                    if ($this.data("show")) {
                        //已经显示更多
                        $jieshi.parent().css("height", "100px");
                        $jieshi.text(str_sub+"...");
                        $this.text("显示更多");
                        $this.data("show",false);
                    }else{
                        //显示更多
                        $jieshi.parent().css("height", "auto");
                        $jieshi.text(str_jieshi);
                        $this.text("隐藏");
                        $this.data("show",true);
                    }
                });
            } else {
                $jieshi.text(str_jieshi);
            }

        }
    };

    /**
     * 面板类
     * @constructor
     */
    var Panel = function () {

    };
    Panel.prototype.create = function (text) {
        var htmlcode = ['<div class="panel panel-info" style="position:absolute;width: 300px;">',
            '    <div class="panel-heading">',
            '        <h3 class="panel-title">',
            '            <span id="panel-title-name">面板</span>',
            '            <a class="btn-default btn pull-right" id="close" style="margin-top: -8px;">x</a>',
            '        </h3>',
            '    </div>',
            '    <div class="panel-body">',
            '    </div>',
            '</div>'].join("");
        this.$Panel = $(htmlcode).appendTo(document.body);
        var thisPanel = this.$Panel;
        //关闭按钮
        var $btn_close = thisPanel.find("#close").click(function () {
            thisPanel.remove();
        });
        var $panel_title = thisPanel.find("#panel-title-name").text(text);
        this.$panel_body = thisPanel.find("div.panel-body");


        //添加拖拽
        thisPanel.draggable(
            {
                handle: ".panel-heading"
            });

    };
    Panel.prototype.setBody = function ($ele) {
        this.$panel_body.append($ele);
    };

    //页面加载
    $(document).ready(function () {
        //为模态对话框添加拖拽
        $("#modalDialog").draggable(
            {
                handle: ".panel-heading"
            });
        //禁止模态对话框的半透明背景滚动
        $("#myModal").css("overflow", "hidden");

        //划词初始化
        Word.init();
        $(document).mousedown(Word.mousedown).mouseup(Word.mouseup);
    });
</script>
</body>
</html>